<template>
  <div>
    <van-search
      v-model="key"
      show-action
      label="关键字"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>
    <div class="content">
      <h3>搜索记录</h3>
      <div class="search-list">
        <div v-if="searchList.length">
        <span
        @click="spanLink(item)"
        v-for="(item,index) in searchList" :key="index">{{item}}</span>
        </div>
        <p v-else>暂无搜索记录</p>
      </div>
      <div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'search',
  data () {
    return {
      key: '',
      searchList: []
    }
  },
  created () {
    this.init()
  },
  methods: {
    onSearch () {
      let list = localStorage.getItem('searchKey') ? JSON.parse(localStorage.getItem('searchKey')) : []
      list.push(this.key)
      list = [...new Set(list)]
      localStorage.setItem('searchKey', JSON.stringify(list))
      this.init()
      this.$router.push(`/searchlist?key=${this.key}`)
    },
    init () {
      this.searchList = localStorage.getItem('searchKey') ? JSON.parse(localStorage.getItem('searchKey')) : []
    },
    spanLink (key) {
      this.$router.push(`/searchlist?key=${key}`)
    }
  }
}

</script>

<style lang="scss" scoped>
.content{
  h3{
    padding:8px 0 0 10px;
    font-size: 15px;
  }
  .search-list{
    display: flex;
    flex-wrap: wrap;
    padding:8px 0 0 20px;
    span{
      margin: 2px;
      display: inline-block;
      min-width: 30px;
      text-align: center;
      height: 30px;
      line-height: 30px;
      border-radius: 10px;
      background: #f66;
    }
  }
}
</style>
